import store from "@/store/index.js"
export const requestData = {
	// 接口地址
	url: "",
}
let loadingCount = 0;
function errTips(message, tips = true) {
	if (tips) {
		setTimeout(() => {
			uni.showToast({
				title: message,
				icon: "none",
				duration: 1500,
			});
		}, 0)

	}
}
export function startLoading() {
	if (loadingCount++ === 0) {
		uni.showLoading({
			title: "加载中",
			mask: true,
		})
	}
	loadingCount;
}

export function stopLoading() {
	if (loadingCount-- === 1) {
		uni.hideLoading();
	}
}

async function requestSuccessHandler(param, response) {
	let data = response.data;
	if (data.code === 0) {
		return data.data || data
	} else {
		// console.log("error -> ", data);
		switch (data.code) {
			case 4700:
				// errTips("用户登录失效，请重新登录")
				const pages = getCurrentPages()
				if (pages.length === 0 || pages[pages.length - 1].route !==
					"/pages/login/index") {
					store.commit("user/CLEAR_USER_TOKEN")
					uni.reLaunch({
						url: "/pages/login/index"
					})
				}
				break;
			case 4500:
				errTips(data.message, param.tips);
				break;
			case 4800:
				errTips(data.message, param.tips);
				break;
			case 4810:
				errTips(data.message, param.tips);
				break;
			default:
				errTips('网络异常，请稍后..', param.tips);
				break;
		}
	}
}

/**
 *  @param { Object } param 请求配置项
 * @return { Promise } 异步的请求结果
*/
export function request(param) {
	return new Promise((resolve, reject) => {
		if (param.loading) {
			startLoading();
		}
		uni.request({
			// 接口地址
			url: requestData.url,
			// 参数
			data: param.data,
			// 请求头
			header: {
				Authorization: "token",
			},
			// 请求方式 必须是大写 默认GET
			method: requestData.method ? requestData.method : "GET",
			// 请求超时时间
			timeout: 10000,
			dataType: "json",
			success: (res) => {
				requestSuccessHandler(param, res).then(resolve).catch(reject);
			},
			fail: (err) => {
				err.message = "请求出现异常，请联系管理员或稍后再试";
				errTips(err.message,param.tips);
				reject(err);
			},
			complete: () => {
				param.loading && stopLoading();
			}
		});
	})
}

export function upload(filePath) {
	return new Promise((resolve, reject) => {
		startLoading();
		// console.log("filePath",filePath);
		uni.uploadFile({
			url: requestData.url,
			header: {
				Authorization: "token"
			},
			name: "file",
			timeout: 10000,
			filePath: filePath.data.filePath,
			success(response) {
				requestSuccessHandler({
					tips: true,
					loading: true,
				}, response).then(res => {
					// console.log(res);
					resolve(res)
				}).catch(reject);
			},
			fail(err) {
				// console.log("fail -> ", err);
				err.message = "请求出现异常，请联系管理员或稍后再试";
				errTips(err.message, opt.tips);
				reject(err);
			},
			complete: stopLoading,
		})
	})
}